const http = require('http');
const url = require('url');
const qs = require('querystring')
const ioredis = require('ioredis');
const redis = new ioredis();
http.createServer((req, res) => {
    try {
        const urlObject = url.parse(req.url);
        const { pathname } = urlObject;
        if (pathname === '/bottle') {
            handleReq(req, res, redis)
        } else {
            throw '22'
        }

    } catch (error) {
        res.statusCode = 200
        res.write(JSON.stringify(error))
        res.end()
    }
}, {}).listen(3000, () => {
    console.log('app is running')
})
function handleReq(req, res, redis) {
    if (req.method === 'GET') {
        const urlObject = url.parse(req.url);
        const { query } = urlObject;
        const { user, type = 'all' } = qs.parse(query);
        if (user && type) {
            res.statusCode = 200;
            res.setHeader('content-type', 'application / json; charset = utf - 8');
            redis.get(user + type, (error, data) => {
                if (error) throw error
                console.log(data)
                res.write(JSON.stringify({ "code": 1, "msg": data }))
                res.end()
            })
        }
    }
    if (req.method === 'POST') {
        let arr = []
        req.on('data', (data) => {
            arr.push(data)
        })
        req.on('end', () => {
            const result = qs.parse(Buffer.concat(arr).toString())
            const { owner, type = 'all', time, content } = result;
            if (owner && type && time && content) {
                redis.set(owner + type, JSON.stringify({ owner, type, time, content }), (error) => {
                    if (error) throw error
                    console.log('写入成功')
                })
            }
        })
        res.statusCode = 200
        res.write(JSON.stringify({ code: 1, msg: 'ok' }))
        res.end()
    }
}
